#!/bin/bash

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"

#THEME_FILE_NAME="$1"
REQUEST="$1"

SYMLINK_NAME=current

cd $SCRIPT_DIR

FISH_THEME_DIR="$SCRIPT_DIR/fish/theme"
VIM_THEME_DIR="$SCRIPT_DIR/vim/theme"
XRESOURCES_DIR="$SCRIPT_DIR/Xresources.d"
XRESOURCES_FILE="$HOME/.Xresources"
XRESOURCES_THEME_DIR="$XRESOURCES_DIR/theme"

THEME_DIRS=("$FISH_THEME_DIR" "$VIM_THEME_DIR" "$XRESOURCES_THEME_DIR")

switch_theme()
{
  local theme_dir="$1"
  local theme_file_name="$2"
  local symlink_name="$SYMLINK_NAME"
  cd "$theme_dir"
  if test -f "$theme_file_name"
  then
    ln -sf "$theme_file_name" "$symlink_name"
    echo "Trace: $theme_dir: $theme_file_name linked to $symlink_name."
  else
    echo "Exit: $theme_file_name doesn't exist in $theme_dir, not linked."
    exit 1
  fi
}

xrdb_exists()
{
  command -v xrdb > /dev/null
}

xresources_file_exists()
{
  test -e "$XRESOURCES_FILE"
}

xresources_ready()
{
  xrdb_exists && xresources_file_exists
}

switch_theme_xresources()
{
  if xresources_ready
  then
    echo "Trace: Xresources ready, will switch Xresources theme."
    local theme_file_name="$1"
    switch_theme "$XRESOURCES_THEME_DIR" "$theme_file_name"
    xrdb -load "$XRESOURCES_FILE"
  else
    echo "Warning: Xresources not ready, will not switch Xresources theme."
  fi
}

switch_to_dark()
{
  local primary_theme=tempus_future.dark
  switch_theme "$VIM_THEME_DIR" "$primary_theme"
  switch_theme_xresources "$primary_theme"

  local fallback_theme=tokyonight.night
  switch_theme "$FISH_THEME_DIR" "$fallback_theme"
}

switch_to_light()
{
  local primary_theme=tempus_totus.light
  switch_theme "$VIM_THEME_DIR" "$primary_theme"
  switch_theme_xresources "$primary_theme"

  local fallback_theme=tokyonight.day
  switch_theme "$FISH_THEME_DIR" "$fallback_theme"
}

case "$REQUEST" in
  dark | night)
    switch_to_dark
    ;;
  light | day)
    switch_to_light
    ;;
  *)
    echo "Error: ${REQUEST:--no request-} is not a valid request."
    exit 1
    ;;
esac

 #for theme_dir in "${THEME_DIRS[@]}"
 #do
 #  switch_theme "$theme_dir" "$THEME_FILE_NAME" "$SYMLINK_NAME"
 #done
